package com.hopital5.zhangyz.service;

import com.hopital5.zhangyz.model.Activity;
import com.hopital5.zhangyz.model.ActivityActivityItem;
import com.hopital5.zhangyz.model.ActivityItem;
import com.hopital5.zhangyz.model.People;
import com.hopital5.zhangyz.repository.ActivityItemRepository;
import com.hopital5.zhangyz.repository.ActivityRepository;
import com.hopital5.zhangyz.repository.PeopleRepository;
import com.hopital5.zhangyz.vo.request.ActivityVoRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
public class ActivityService {
    @Autowired
    ActivityRepository activityRepository;
    @Autowired
    PeopleRepository peopleRepository;
    @Autowired
    ActivityItemRepository activityItemRepository;

    public Activity save(ActivityVoRequest activityVoRequest) {
        List<ActivityItem> activityItems = activityItemRepository.findAll(activityVoRequest.getActivityItemIds());
        Activity activity = Activity.builder()
                .beginDate(activityVoRequest.getBeginDate())
                .endDate(activityVoRequest.getEndDate())
                .name(activityVoRequest.getName())
                .build();
        peopleRepository.findByLabels_id(activityVoRequest.getLabelId()).stream()
                .flatMap(people -> activityItems.stream().map(activityItem -> ActivityActivityItem.builder()
                        .activityItem(activityItem)
                        .people(people)
                        .number(BigDecimal.ZERO)
                        .build())).forEach(activity::addActivityActivityItem);
        return activityRepository.save(activity);
    }

    @Transactional
    public Activity update(ActivityVoRequest activityVoRequest) {
        Activity activity = activityRepository.findOne(activityVoRequest.getActivityId());
        activity.setBeginDate(activityVoRequest.getBeginDate());
        activity.setEndDate(activityVoRequest.getEndDate());
        activity.setName(activityVoRequest.getName());
        return activity;
    }

    public Activity findOne(Long id) {
        return activityRepository.findOne(id);
    }

    public void delete(Long id) {
        activityRepository.delete(id);
    }

    public void delete(Activity activity) {
        activityRepository.delete(activity);
    }
}

